<template>
  <!-- 考勤班次添加 -->
  <div class="contractInfo box">
    <el-divider content-position="left">{{
      $route.query.mode == "add" ? "添加班次" : "编辑班次"
    }}</el-divider>
    <div class="formBox">
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="班次名称" prop="shiftName">
          <el-input
            v-model="form.shiftName"
            clearable
            placeholder="请输入班次名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="班次类型" prop="shiftType">
          <el-select
            v-model="form.shiftType"
            placeholder="请选择班次类型"
            style="width: 100%"
            remote
            remote-show-suffix
            clearable
            disabled
          >
            <el-option
              v-for="item in shiftType"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间设置" style="width: 100%" required>
          <el-table
            :data="periodList"
            :span-method="objectSpanMethod"
            border
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column prop="periodName" label="时段名称" width="400">
              <template #default="scope">
                <el-input
                  v-model="scope.row.periodName"
                  placeholder="请输入时段名称"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="100">
            </el-table-column>
            <el-table-column prop="time" label="签到/签退时间" width="400">
              <template #default="scope">
                <el-time-picker
                  v-model="scope.row.time"
                  placeholder="请选择时间"
                  value-format="HH:mm:ss"
                />
                <!-- <el-time-picker
                  v-model="scope.row.time"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  value-format="HH:mm:ss"
                /> -->
              </template>
            </el-table-column>
            <el-table-column prop="inOutClock" label="设置" width="150">
              <template #default="scope">
                <!-- <el-switch
                  v-model="scope.row.inOutClock"
                  :inactive-value="1"
                  :active-value="0"
                ></el-switch> -->
                <el-checkbox
                  v-model="scope.row.inOutClock"
                  :true-label="0"
                  :false-label="1"
                  label="打卡"
                />
              </template>
            </el-table-column>
            <el-table-column prop="clockSetting" label="打卡设置" width="350">
              <template #default="scope">
                <el-radio-group
                  v-model="scope.row.clockSetting"
                  class="radioList"
                >
                  <el-radio
                    :label="item.value"
                    v-for="item in clockSetList"
                    :key="item.value"
                    >{{ item.name }}</el-radio
                  >
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="pointsName" label="考勤点">
              <template #default="scope">
                <div class="location">
                  <p v-for="item in scope.row.pointsName" :key="item">
                    {{ item }}
                  </p>
                </div>
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="small"
                  @click="selectLocation"
                  >选择考勤点</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="部门/人员" required style="width: 100%">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="selectPerson"
            >选择部门/人员</el-button
          >
          <div class="userList">
            <!-- <div
              class="item"
              v-for="item in selectedPerson"
              :key="item.departmentName"
            >
              <p class="name">{{ item.departmentName }}：</p>
              <p class="value">{{ item.names.join("，") }}</p> 
              
            </div> -->
            <p class="value">{{ selectedPerson }}</p>
          </div>
        </el-form-item>
        <el-form-item label="可补卡次数" style="width: 100%">
          <el-input-number v-model="form.replaceCount" />
        </el-form-item>
        <el-form-item label="开始打卡日期" prop="beginTime">
          <el-date-picker
            v-model="form.beginTime"
            type="date"
            placeholder="请选择打卡日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否跳过法定节假日打卡" style="width: 100%">
          <!-- <el-switch v-model="form.meta.enabled" /> -->
          <el-switch
            v-model="form.automaticLeave"
            :active-value="0"
            :inactive-value="1"
          ></el-switch>
        </el-form-item>
        <el-form-item
          label="日期"
          prop="weekValue"
          style="width: 100%"
          v-show="form.automaticLeave == 1"
        >
          <el-checkbox-group v-model="form.weekValue">
            <el-checkbox
              :label="item.value"
              v-for="item in week"
              :key="item.value"
              :checked="item.checked"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </div>
  </div>
  <!-- 选择考勤点 -->
  <select-location
    ref="selectLocation"
    @showLocation="showLocation"
  ></select-location>

  <!-- 选择部门人员 -->
  <select-person ref="selectPerson" @showPerson="showPerson"></select-person>
</template>
<script>
import { queryTypeByDic } from '@/utils/getData'
import selectLocation from './components/selectLocation.vue'
import selectPerson from './components/selectPerson.vue'
export default {
  name: 'shiftAdd',
  data () {
    return {
      isSaveing: false,
      selectContractLoading: false,
      //表单数据
      form: {
        shiftName: '',//班次名称
        shiftType: 1,//班次类型
        punchClock: '',//打卡日期
        beginTime: '',//开始打卡日期
        recurry: '',//已选日期
        weekValue: [], //默认显示日期
        automaticLeave: 0,//是否跳过法定节假日打卡：0是1否
        replaceCount: 0
      },
      shiftType: [],//班次类型列表
      clockSetList: [],//打卡设置列表
      selectedPerson: '',//已选择的人员
      selectedPersonList: [],//已选人员详细列表
      selectedPersonIds: [],//已选择的部门人员id
      selectedLocation: [],//已选择的考勤点
      //验证规则
      rules: {
        shiftName: [
          { required: true, message: '请输入班次名称' }
        ],
        shiftType: [
          { required: true, message: '请选择班次类型', trigger: 'change' }
        ],
        beginTime: [
          { required: true, message: '请选择开始打卡时间', trigger: 'change' }
        ],
        punchClock: [
          { required: true, message: '请选择打卡日期', trigger: 'change' }
        ],
        selectedPerson: [
          { required: true, message: '请选择部门/人员', trigger: 'change' }
        ],
        weekValue: [
          {
            type: 'array',
            required: true,
            message: '请至少选择日期',
            trigger: 'change',
          },
        ],
      },
      periodList: [{//时间表
        periodName: '时段1',//时段名称
        clockSetting: 2,//打卡设置
        type: '签到',
        time: [],
        // inTime: '',//签到
        // outTime: '签退',//签退
        pointsName: '',//考勤点
        inOutClock: 0//是否需要打卡 0是 1否
      }, {
        periodName: '时段1',//时段名称
        clockSetting: 2,//打卡设置
        type: '签退',
        time: [],
        // inTime: '签到',//签到
        // outTime: '签退',//签退
        pointsName: '',//考勤点
        inOutClock: 0//是否需要打卡 0是 1否
      },],
      week: [
        {
          label: '周一',
          value: 2,
          checked: true
        },
        {
          label: '周二',
          value: 3,
          checked: true
        }, {
          label: '周三',
          value: 4,
          checked: true
        },
        {
          label: '周四',
          value: 5,
          checked: true
        },
        {
          label: '周五',
          value: 6,
          checked: true
        },
        {
          label: '周六',
          value: 7,
          checked: false
        },
        {
          label: '周日',
          value: 1,
          checked: false
        }
      ],
      pointList: []//考勤点
    }
  },
  components: {
    selectLocation,
    selectPerson
  },
  mounted () {
    this.getType()
    if (this.$route.query.mode == 'edit') {
      this.getDetail()
    }

  },
  methods: {
    async getType () {
      // 获取班次类型
      this.shiftType = await queryTypeByDic('shiftType')
      // 获取打卡设置
      this.clockSetList = await queryTypeByDic('clockSet')
    },

    // 获取班次详情
    async getDetail () {
      let { data } = await this.$API.attendance.getShiftDetail.post({ id: this.$route.query.id })
      console.log(data)
      this.form.shiftName = data.shiftName
      this.form.shiftType = data.shiftType
      this.form.beginTime = data.beginTime
      this.form.automaticLeave = data.automaticLeave
      this.form.replaceCount = data.replaceCount
      let arr = data.recurry.split(',')
      this.form.weekValue = arr.map(Number)
      console.log(this.form.weekValue)
      this.periodList[0].periodName = data.periodList[0].periodName
      this.periodList[0].time = data.periodList[0].inTime
      // this.periodList[0].time.push(data.periodList[0].inTime)
      // this.periodList[0].time.push(data.periodList[0].inOutTime)
      // this.periodList[1].time.push(data.periodList[0].outBeginTime)
      // this.periodList[1].time.push(data.periodList[0].outTime)
      this.periodList[1].time = data.periodList[0].outTime
      this.periodList[0].inOutClock = data.periodList[0].inClock
      this.periodList[1].inOutClock = data.periodList[0].outClock
      this.periodList[0].clockSetting = data.periodList[0].inClockSetting
      this.periodList[1].clockSetting = data.periodList[0].outClockSetting
      this.periodList[0].pointsName = data.periodList[0].pointsName
      data.adList && data.adList.forEach(item => {
        this.selectedPersonIds.push(item.adminId)
        this.selectedPersonList.push({ departmentId: item.departmentId, adminId: item.adminId })
      })
      console.log(this.selectedPersonIds)
      this.selectedPerson = data.adminNames
      this.showLocation(data.periodList[0].pointsList)
    },

    // 选择考勤点
    selectLocation () {
      // if (this.$route.query.mode == 'edit') {
      this.$refs.selectLocation.open(this.periodList[0].pointsName)
      // } else {
      //   this.$refs.selectLocation.open()
      // }
    },

    showLocation (list) {
      this.periodList[0].pointsName = []
      list.forEach(item => {
        this.periodList[0].pointsName.push(item.pointsName)
      })
      this.pointList = list
    },

    save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          // 时间表
          let timeItem = {
            periodName: this.periodList[0].periodName,
            inTime: this.periodList[0].time,//上班时间
            // inOutTime: this.periodList[0].time[1],//上午上班结束时间
            outTime: this.periodList[1].time,//下班时间
            // outBeginTime: this.periodList[1].time[0],//下午午上班结束时间
            inClock: this.periodList[0].inOutClock,
            outClock: this.periodList[1].inOutClock,
            inClockSetting: this.periodList[0].clockSetting,
            outClockSetting: this.periodList[0].clockSetting,
            pointsId: '',
          }
          if (timeItem.inTime == '') {
            this.$message.error("请选择签到时间")
            return
          }

          if (timeItem.outTime == '') {
            this.$message.error("请选择签退时间")
            return
          }

          if (this.periodList[0].pointsName.length == 0) {
            this.$message.error("请选择考勤点")
            return
          }

          if (this.selectedPersonIds.length == 0) {
            this.$message.error("请选择部门/人员")
            return
          }

          let points = []
          this.pointList.forEach(item => {
            points.push(item.id)
          })
          timeItem.pointsId = points.join(',')

          let data = {
            shiftName: this.form.shiftName,
            shiftType: this.form.shiftType,
            beginTime: this.form.beginTime,
            automaticLeave: this.form.automaticLeave,
            recurry: this.form.automaticLeave == 1 ? this.form.weekValue.join(',') : '',
            periodList: [timeItem],
            adminIds: this.selectedPersonIds
          }
          console.log(data)
          let mode = this.$route.query.mode
          this.isSaveing = true
          let res = null
          if (mode == 'add') {
            res = await this.$API.attendance.addshift.post(data)
          } else if (mode == 'edit') {
            data.id = this.$route.query.id
            res = await this.$API.attendance.updateShift.post(data)
          }
          this.isSaveing = false
          if (res.code == 200) {

            this.$emit('success', this.form, this.mode)
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: '/person/attendance'
            })
            this.$message.success("操作成功")
          } else {
            this.$alert(res.message, "提示", { type: 'error' })
          }
        }
      })
    },
    objectSpanMethod ({ rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
      if (columnIndex === 4) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
      if (columnIndex === 5) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },

    // 选择部门/人员
    selectPerson () {
      this.$nextTick(() => {
        this.$refs.selectPerson.open(this.selectedPersonIds)

      })
    },

    // 显示部门人员
    showPerson (list) {
      console.log(list)
      let arrId = []
      let arrName = []
      list.forEach(item => {
        arrId.push(item.id)
        arrName.push(item.name)

      })

      this.selectedPersonIds = arrId
      this.selectedPerson = arrName.join(',')
      console.log(this.selectedPersonIds)
    },

    // 取消班次添加
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: '/person/attendance'
      })
    },

    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  }

}

</script>
<style lang='scss' scoped>
.box {
  margin: 10px;
}

.formBox {
  padding: 30px;
  background: #fff;
  .el-form {
    width: 100%;
  }
}
.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}

.radioList {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.location {
  margin-bottom: 20px;
}

.userList {
  width: 100%;
  margin-top: 10px;
  font-size: 16px;
  .item {
    display: flex;
  }
  .name {
    margin-right: 10px;
    font-weight: 600;
  }
}
</style>